﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


using DotNet.Business;
using DotNet.Model;
using DotNet.Common;
using System.Text;
using System.Collections.Generic;

using System.Net.Mail;

public partial class Admin_adminQuestion:basePage
{
    AnswerBll aBll = new AnswerBll();
    QuestionBll qBll = new QuestionBll();
    QuestionClassBll qcBll = new QuestionClassBll();
    productBll pBll = new productBll();
    StringBuilder str = new StringBuilder();
    productClassBll pcBll = new productClassBll();
    UserBll userBll = new UserBll();
    private static readonly object objSync = new object();
    public string input = "<input id=\"HiddenUrl\" type=\"hidden\" value=\"&CurrentIndex=1\" />";
    int pageSize = 10;
    public int uid = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.QueryString["action"] != null)
            {
                string action = Request.QueryString["action"].ToString();
                switch (action.Trim())
                {
                    case "show":
                        getQuestionAnswerContent(Convert.ToInt32(Request.QueryString["qid"]));
                        break;      
                    case "answer":
                        AnswerQuestion();
                        break;
                    case "del":
                        delQuestion();
                        break;
                    case "appendProductClassDp":
                        ApendProductClassDp();
                        break;
                    case "appendProductId":
                        AppendProductIdDp();
                        break;
                    case "close":
                        closeQuestion();
                        break;
                    case "delete":
                        delete();
                        break;
                    case "MoveAll":
                        move();
                        break;
                    default:
                        break;
                }
            }
            BindQuestion();
        }
    }
    #region 绑定问题
    public void BindQuestion()
    {   
        if (Request.QueryString["CurrentIndex"] != null)
        {
            _currentIndex = Convert.ToInt32(Request.QueryString["CurrentIndex"]);
        }
        if (Request.QueryString["user"]!=null)
        {
            _user = Request.QueryString["User"].ToString();
        }
        if (Request.QueryString["qcid"]!=null)
        {
            _questionClassID = Convert.ToInt32(Request.QueryString["qcid"]);
        }
        if (Request.QueryString["pid"]!=null)
        {
            _productId = Request.QueryString["pid"].ToString();
        }
        if (Request.QueryString["state"] != null && Request.QueryString["state"]!="")
        {
            _state=Convert.ToInt32(Request.QueryString["state"]);
        }
        DataTable dt = qBll.pagingForQuestions(_currentIndex, pageSize, _user, _questionClassID, _productId,_state);
        if (dt.Rows.Count == 0 && _currentIndex > 1)
        {
            _currentIndex = _currentIndex - 1;
            dt = qBll.pagingForQuestions(_currentIndex, pageSize, _user, _questionClassID,_productId,_state);
        }
        input = "<input id='HiddenUrl' type='hidden' value='&CurrentIndex=" + _currentIndex + "' />";
        this.Repeater1.DataSource = dt;
        this.Repeater1.DataBind();       
    }

    #endregion

    #region 关闭问题
    public void closeQuestion()
    {
        Question question = new Question();
        question = qBll.GetModel(Convert.ToInt32(Request.QueryString["qid"]));
        question.questionState = true;
        if (qBll.Update(question))
        {
            Response.Write("1");
            Response.End();
        }
    }
    #endregion

    #region 自定义下拉框
    public string QuestionClassDp(string id)
    {
        StringBuilder str = new StringBuilder();
        IList<QuestionClass> qcList = qcBll.GetModelByFid(0);
        str.Append("<select name='selectDp' onclick=\"showCheckbox()\" id='" + id + "' style='width:150px;'>");
        str.Append("<option value='0'>--选择问题类别--</option>");
        foreach (QuestionClass qc in qcList)
        {
            str.Append("<option value='" + qc.questionClassID + "'>" + qc.questionClassName + "</option>");
        }
        str.Append("</select>");

        return str.ToString();
    }
    #endregion

    #region 问题分页按钮
    public void QuestionPagingHtml()
    {
        string str = null;
        int count = 0;
        count = qBll.getRecordCount(_user, _questionClassID, _productId,_state);
        int pcount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
        str = "页次：" + _currentIndex + "/" + pcount + "  每页" + pageSize + " 总收录数据" + count + "条";
        str += HtmlControls.pagIng(_currentIndex, pcount, "adminQuestion.aspx?state="+_state+"&pid=" + _productId + "&user=" + _user + "&qcid=" + _questionClassID + "&CurrentIndex", "pageaa", "pagecurrent");
        Response.Write(str);

    }
    #endregion

    #region 状态维护属性
    public int _currentIndex = 1;
    public string _user="";
    public int _questionClassID = 0;
    public string _productId = "";
    public int? _state = null;
    #endregion

    #region 绑定关闭图片
    public string closeImg(object state, object qid)
    {
        string img = "";
        if (state.ToString() == "False")
        {
            img = "<img id=img" + qid + " name=\"closeImg\" style=\"cursor:pointer\" title=\"" + qid + "\" onclick=\"closeQuestion(this.title)\" src=\"../DotNet_net/Skins/testyle500kv/images/close1.gif\" />";
        }
        return img;
    }
    #endregion

    #region 问答内容
    public void getQuestionAnswerContent(int fid)
    {
        StringBuilder sb = new StringBuilder();
        IList<Question> qList = qBll.GetModelByFid(fid);
        Question question = qBll.GetModel(fid);       
        IList<Answer> answerList = aBll.GetListByQuestionID(question.questionID);
        sb.Append("提问时间：" + question.postTime.ToString() + "    最后回复时间：");
        string endTime = "--/--";
        int lenth = sb.Length;
        int endQid = question.questionID;
        sb.Append("<div class=\"faq_info\">" + question.description + "<br><br>产品：" + getProductName(question.productID) + "</div>");
        sb.Append("<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin-top:5px;\">");
        foreach (Answer answer in answerList)
	    {
            sb.Append(" <tr><td class=\"phuida\">" + answer.replyTime + "<span class=\"style2\" style=\"color:green\">" + answer.adminName + "</span> 回答 :</td></tr>");
            endTime = answer.replyTime.ToString();
            sb.Append("  <tr><td class=\"phuida1\" style=\"color:green\">" + answer.description + "</td></tr>");
	    }
        
        foreach (Question q in qList)
        {
            sb.Append("<tr id=\"cqT"+q.questionID+"\"><td class=\"phuida\">" + q.postTime + "<span style=\"color:Red\">" + question.userName + "</span> 问 :<img id=img" + q.questionID + " name=\"deleteImg\" style=\"cursor:pointer\" title=\"" + question.questionID + "\" onclick=\"deleteQuestion(this.title,"+q.questionID+")\" src=\"../DotNet_net/Skins/testyle500kv/images/delete.gif\" /></td></tr>");
            sb.Append("<tr id=\"cqD" + q.questionID + "\"><td class=\"phuida1\">" + "<span style=\"color:Red\">" + q.description + "</span>" + "</td> </tr> ");
            endQid = q.questionID;
            foreach (Answer a in aBll.GetListByQuestionID(q.questionID))
            {
                sb.Append("<tr><td class=\"phuida\">" + a.replyTime + "<span style=\"color:green\">" + a.adminName + "</span> 回答 :</td></tr>");
                sb.Append("<tr><td class=\"phuida1\">" + "<span style=\"color:green\">" + a.description + "</span> " + "</td></tr>");
                endTime = a.replyTime.ToString();                
            }
        }
        sb.Insert(lenth, endTime);
        sb.Append("</table>");
        if (question.questionState == false)
        {
            sb.Append("<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"margin-top:10px; border-top:1px solid #a6a79d;\">");
            sb.Append("<tr><td><textarea id=\"txt" + endQid + "\" name=\"textarea\" rows=\"\" style=\"width:260px; height:120px; margin-top:10px;\"></textarea></td></tr>");
            sb.Append("<tr><td><input type=\"button\" class=\"btn\" onclick=\"SubmitQuestion(" + endQid + ",this.title)\" title=\"" + question.questionID + "\"  value=\"我来回答\" /></td></tr>");
            sb.Append("</table>");

        }
        Response.Write(sb.ToString());
        Response.End();
    }
    #endregion

    #region 回答
    public void AnswerQuestion() 
    {
        string contetn = Request.Form["txt"].ToString();
        int qid = Convert.ToInt32(Request.QueryString["qid"]);
        int fid = Convert.ToInt32(Request.QueryString["contentId"]);
        string userName = Request.Form["userName"].ToString();
        bool isSend = Convert.ToBoolean(Request.Form["isSend"]);
       
        Answer answer = new Answer();
        answer.adminName = DotCookie.Read("adminUser");
        answer.description = contetn;
        answer.questionID = qid;
        answer.replyTime = DateTime.Now.ToLocalTime();
        if (answer.description=="")
        {
            Response.Write("1");
            Response.End();
        }
        if (aBll.Insert(answer))
        {
            if (isSend)
            {
                sendEmail(answer,qid,userName);
            }
            getQuestionAnswerContent(fid);
        }
       
    }
    #endregion

    #region 删除问题
    public void delQuestion() 
    {
        int qid=Convert.ToInt32(Request.QueryString["qid"]);
        lock (objSync)
        {
            qBll.DeleteByFid(qid);
            qBll.Delete(qid);
        } 
    }
    #endregion

    #region 删除
    public void delete() 
    {
        if (qBll.Delete(Convert.ToInt32(Request.QueryString["qid"])))
        {
            getQuestionAnswerContent(Convert.ToInt32(Request.QueryString["fid"]));
        }
    }
    #endregion

    #region 绑定问题类别选项
    public string QuestionClassDp()
    {
        str.Remove(0, str.Length);
        IList<QuestionClass> qcList = qcBll.GetModelByFid(0);
        str.Append("<option selected=\"selected\" value='0'>请选择问题类别</option>");
        foreach (QuestionClass qc in qcList)
        {
            str.Append("<optgroup style=\"color:Red;\" label=\"" + qc.questionClassName + " \">" + qc.questionClassName + "</optgroup>");
            foreach (QuestionClass qcModel in qcBll.GetModelByFid(qc.questionClassID))
            {
                str.Append("<option title=\"" + qcModel.Questionstate + "\" value=\"" + qcModel.questionClassID + "\">" + qcModel.questionClassName + "</option>");
            }
        }
        return str.ToString();
    }

    #endregion 

    #region 帮定用户下拉框
    public string UserDp() 
    {
        str.Remove(0,str.Length);
        IList<User> userList = userBll.GetModel();
        str.Append("<option selected=\"selected\" value=''>没有选择用户</option>");
        foreach (User  u in userList)
        {
            str.Append("<option title=\"" +u.userID  + "\" value=\"" + u.userName + "\">" +u.userName + "</option>");
        }
        return str.ToString();
    }
    #endregion

    #region 追加产品类别选项
    public void ApendProductClassDp()
    {
        str.Remove(0, str.Length);
        IList<productClass> pcList = pcBll.GetModel();
        str.Append("<option value=\"0\" selected=\"selected\">请选择产品类别</option>");
        foreach (productClass pc in pcList)
        {
            str.Append("<option value=\"" + pc.pClassId + "\">" + pc.pClassName + "</option>");
        }
        Response.Write(str.ToString());
        Response.End();
    }
        #endregion

    #region 追加产品选项
    public void AppendProductIdDp()
    {
        int pid = Convert.ToInt32(Request.QueryString["ProductID"]);
        if (pid >= 0)
        {
            str.Remove(0, str.Length);
            IList<product> pList = pBll.pagingForProduct(1, 100, pid, 0, false);
            str.Append("<option value=\"0\" selected=\"selected\">请选择产品</option>");
            foreach (product p in pList)
            {
                str.Append("<option value=\"" + p.productId + "\">" + p.productName + "</option>");
            }
            if (pList.Count == 0)
            {
                str.Append("<option value=\"\">该类别下无产品</option>");
            }
            Response.Write(str.ToString());
            Response.End();
        }
        else
        {
            Response.Write("1");
            Response.End();
        }
    }
    #endregion

    #region 根据产品id获得产品名称
    public string getProductName(int productid)
    {
        if (productid != 0)
        {
            product product = pBll.GetModel(productid);
            return  product.productName;
        }
        else 
        {
            return "没有关联产品！";
        }
    }
    #endregion

    #region 发送邮件
    public void sendEmail(Answer answer,int qid,string userName)
    {
        User user=userBll.GetModel(userName);
        Question question = qBll.GetModel(qid);
        MailAddressCollection mac=new MailAddressCollection();
        mac.Add(user.userEmail);
        string title = "特试特科技有限公司对你的问题的答复";
        str.Remove(0, str.Length);
        str.AppendFormat("您的问题：{0}\n", question.title);
        str.AppendFormat("问题内容：{0}\n", question.description);
        str.AppendFormat("提问时间：{0}\n", question.postTime);
        str.AppendFormat("问题答复：{0}\n", answer.description);
        str.AppendFormat("答复时间：{0}\n", answer.replyTime);
        str.AppendFormat("查看详细：{0}\n", "http://testyle.500kv.com/zh/index.aspx");
        MailSender.Send(mac, title, str.ToString(), false, null);
        
    }
    #endregion

    #region ajax批量移动
    public void move() 
    {
        string qcid = Request.QueryString["id"].ToString();
        string qids = Request.QueryString["qids"].ToString();
        try
        {
            if (qids.Contains(","))
            {
                string[] idParam=qids.Split(',');
                if (qBll.Update(idParam,qcid))
                {

                }	         
            }
            else
            {
                string[] idParam={qids};
                if (qBll.Update(idParam,qcid))
                {

                }
            }
       
        }
        catch (Exception)
        {
            
            throw;
        }       
    }     
    #endregion

    #region 根据问题类别id获得问题类别名称
    public string getQuestionClassName(object qcid) 
    {
        int questionClassID = Convert.ToInt32(qcid);
        return qcBll.GetModel(questionClassID).questionClassName;
    }
    #endregion

    #region 获得最新的提问
    public string getCount(object fid,object state) 
    {
        if (Convert.ToBoolean(state) == false)
        {
            int qid = Convert.ToInt32(fid);
            IList<int> intList = new List<int>();
            IList<Question> qList = qBll.GetModelByFid(qid);
            intList.Add(qid);
            foreach (Question q in qList)
            {
                intList.Add(q.questionID);
            }
            Answer answer = aBll.getLastAnswer(intList);
            if (answer.answerID > 0)
            { 
                IList<Question> questionList = qBll.getLastQuestion(intList);
                if (questionList.Count>0)
                {
                    return questionList.Count+"条新问题没有回复";
                }
            }
            else 
            {
                return "新问题没有回复";
            }
        }
        return ""; 
    }
    #endregion



}
